package com.longxi.tianjintianbao.ui.presenter.repair_publish;

import android.app.Activity;
import android.content.Intent;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.HttpResult;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.listener.SelectAreaListener;
import com.longxi.tianjintianbao.model.Build;
import com.longxi.tianjintianbao.ui.adapter.multitype.AreaViewBinder;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.view.repair_publish.ISelectAreaAtView;
import com.longxi.tianjintianbao.utils.MyUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 如果是公共区域维修可能只选小区
 * 如果是客户区域维修需要精确到客户住的位置
 */

public class SelectAreaAtPresenter extends BasePresenter<ISelectAreaAtView> {

    public static String REPAIRAREA = "REPAIRAREA";//客户区域0 公共区域1
    private MultiTypeAdapter adapter;
    private Items items;
    //记录当前是第几层 当到达第四层时点击finsh activity
    private int floor = 1;

    //头部标题
    String title = "";
    //详细地址
    private String address = "";
    //详细地址
    private String area = "";
    //维修区域
    String repairarea = "0";
    //回传人名
    String custname = "";
    //回传人id
    String contactsid = "";
    //回传人电话
    String custphone = "";

    boolean isLoadBuild = false;//判断是否已点击加载

    public SelectAreaAtPresenter(BaseActivity context) {
        super(context);
    }

    public void setBar() {
        Intent intent = mContext.getIntent();
        repairarea =intent.getStringExtra(AppConst.REPAIRAREA);
        mContext.setTitle("请选择小区");
        mContext.setTvLeft(MyUtils.getString(R.string.back));
    }

    public void initAdapter(){
        if(adapter == null){
            adapter = new MultiTypeAdapter();
            /* 注册类型和 View 的对应关系 */

            SelectAreaListener selectAreaListener = new SelectAreaListener() {
                @Override
                public void onNextArea(Build build) {
                    floor++;
                    custname = build.getCustname();
                    contactsid = build.getCustid();
                    custphone = build.getCtustphone();
                    getArea(build.getBuildid() + "", build.getBuild());
                }
            };
            adapter.register(Build.class, new AreaViewBinder(selectAreaListener));
            getView().getRvContent().setAdapter(adapter);
        }
    }

    /**
     * 获取区域
     * @param buildId
     * @param buildName
     */
    public void getArea(String buildId, String buildName){
        if(floor == 1){
            getLocalCommunity();
            return;
        }else if(floor == 2){
            area = buildName;
        }else{
            if(isLoadBuild){
                MyUtils.showToast("加载中...请勿重复点击");
                return;
            }
            isLoadBuild = true;
            address += buildName;
        }

        if("1".equals(repairarea)){
            fh(buildId, area, address);
            return;
        }

        title = "地址";
//        MyUtils.showToast("加载"+title);
        mContext.showWaitingDialog("加载"+title);
        mContext.setTitle("选择"+title);
        getBuilds(buildId);
    }

    /**
     * 获取本地的小区信息
     */
    public void getLocalCommunity(){
        String buildid = MyApplication.loginUser.buildid;
        String build = MyApplication.loginUser.build;
        List<String> buildidList= Arrays.asList(buildid.replace(" ", "").split(","));
        List<String> buildList= Arrays.asList(build.replace(" ", "").split(","));
        List<Build> localBuilds = new ArrayList<>();
        for (int i = 0; i < buildidList.size(); i++) {
            Build localBuild = new Build();
            localBuild.setBuildid(Integer.parseInt(buildidList.get(i)));
            localBuild.setBuild(buildList.get(i));
            localBuilds.add(localBuild);
        }
        items = new Items();
        items.addAll(localBuilds);
        adapter.setItems(items);
        adapter.notifyDataSetChanged();
    }

    /**
     * 从服务器端获取楼盘信息
     * @param buildId
     */
    public void getBuilds(String buildId){

        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.userid);
            object.put("buildid", buildId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ApiRetrofit.getInstance().getBuilds(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<Build>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                isLoadBuild = false;
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(HttpResult<Build> buildResponse) {
                mContext.hideWaitingDialog();
                isLoadBuild = false;
                if(buildResponse.getCode() == 103){
                    fh(buildId, area, address);
                    return;
                }
                if(buildResponse.getCode() != 0){
                    fh(buildId, area, address);
                    return;
                }
                items = new Items();
                items.addAll(buildResponse.getData());
                adapter.setItems(items);
                adapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 返回上一个页面值回传数据
     * @param buildId
     * @param area
     * @param address
     */
    public void fh(String buildId, String area, String address){
        Intent intent = new Intent();
        intent.putExtra("buildId", buildId);
        intent.putExtra("area", area);
        intent.putExtra("address", address);
        intent.putExtra("custname", custname);
        intent.putExtra("contactsid", contactsid);
        intent.putExtra("custphone", custphone);
        mContext.setResult(Activity.RESULT_OK, intent);
        mContext.finish();
    }

}
